package com.gnerv.pabu.plugin.annotation;

import com.gnerv.pabu.plugin.config.AnnotationSettings;
import com.gnerv.pabu.plugin.utils.DateUtils;
import com.gnerv.pabu.plugin.utils.VelocityUtils;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 *
 * @Description: [添加类注释]
 * @Author: [Gnerv]
 * @CreateDate: [2020/04/05]
 * </p>
 */
public class ClassAnnotation extends AnAction {

    private static final Pattern PATTERN = Pattern.compile("(\\/\\*|@\\S|public class|public interface|public @interface|public enum)+");

    private static final String FILE_TYPE_JAVA = "JAVA";

    private AnnotationSettings annotationSettings;

    @Override
    public void actionPerformed(AnActionEvent event) {
        final FileEditor fileEditor = event.getData(PlatformDataKeys.FILE_EDITOR);
        VirtualFile file = fileEditor.getFile();
        String fileType = file.getFileType().getName();
        if (FILE_TYPE_JAVA.equals(fileType)) {
            Map<String, Object> map = new HashMap<>();
            final Editor editor = event.getRequiredData(CommonDataKeys.EDITOR);
            final Project project = event.getRequiredData(CommonDataKeys.PROJECT);
            final Document document = editor.getDocument();
            String classDescribe = Messages.showInputDialog("类说明", "添加类说明", Messages.getQuestionIcon());
            PropertiesComponent instance = PropertiesComponent.getInstance();
            annotationSettings = ServiceManager.getService(AnnotationSettings.class);
            map.put("author", annotationSettings.getAuthor());
            map.put("createDate", DateUtils.formatNow());
            map.put("description", classDescribe);
            String describe = VelocityUtils.generate(annotationSettings.getTemplateGroup().getTemplates().get(0).getCode(), map);
            Matcher matcher = PATTERN.matcher(document.getText());
            if (matcher.find()) {
                int start = matcher.start();
                WriteCommandAction.runWriteCommandAction(project, () ->
                        document.replaceString(start, start, describe)
                );
            }
        }
    }
}